local DailyGiftExcel = require("excel.DailyGift").gift[1]
local Msg = require("core.Msg")
local Grid = require("bag.Grid")
local BagLogic = require("bag.BagLogic")
local Broadcast = require("broadcast.Broadcast")
local Lang = require("common.Lang")
local RoleUIControl = require("role.RoleUIControl")

firstGridCache = nil
secondGirdCache = nil
thirdGridCache = nil
function sendDailyGift(human)
    local msg = Msg.gc.GC_DAILY_GIFT_QUERY
    msg.status = human.db.dailyGiftStatus
    
    if firstGridCache == nil then
        firstGridCache = {}
        Grid.create(firstGridCache, DailyGiftExcel.first[1], DailyGiftExcel.first[2], DailyGiftExcel.first[3])
        secondGirdCache = {}
        Grid.create(secondGirdCache, DailyGiftExcel.second[1], DailyGiftExcel.second[2], DailyGiftExcel.second[3])
        thirdGridCache = {}
        for i = 1, #DailyGiftExcel.third do
            thirdGridCache[i] = {}
            Grid.create(thirdGridCache[i] , DailyGiftExcel.third[i][1], DailyGiftExcel.third[i][2], DailyGiftExcel.third[i][3])            
        end
        
        Grid.makeItem(firstGridCache, msg.reward[1])
        Grid.makeItem(secondGirdCache, msg.reward[2])
    end    
    if human.db.dailyGiftThirdID < 1 or human.db.dailyGiftThirdID > #DailyGiftExcel.third then
        refreshThirdGrid(human)
    end
    msg.reward[0] = 2
    if thirdGridCache[human.db.dailyGiftThirdID] then
        Grid.makeItem(thirdGridCache[human.db.dailyGiftThirdID], msg.reward[3])
        msg.reward[0] =3
    end    
    Msg.send(msg, human.fd)
end

function refreshThirdGrid(human)
    local start = math.random(1, #DailyGiftExcel.third)
    for i = 1, #DailyGiftExcel.third do
        start = ((start+i)%(#DailyGiftExcel.third)) + 1
        if start ~= human.db.dailyGiftThirdID then
            break
        end
    end
    human.db.dailyGiftThirdID = start
end

function getDailyGift(human)
    if human.db.dailyGiftStatus ~= 1 then
        return
    end  
    if BagLogic.getLeftGrids(human) < 3 then
        Broadcast.sendBroadcast(human, Lang.MOUSE, Lang.SHOP_ERR_BAG_FULL)
        return
    end
    human.db.dailyGiftStatus = 2
    
    BagLogic.addItem(human, DailyGiftExcel.first[1],  DailyGiftExcel.first[3],DailyGiftExcel.first[2], "daily_gift")
    BagLogic.addItem(human, DailyGiftExcel.second[1],  DailyGiftExcel.second[3],DailyGiftExcel.second[2], "daily_gift")
    
    local third = DailyGiftExcel.third[human.db.dailyGiftThirdID]
    if third then
        BagLogic.addItem(human, third[1],  third[3],third[2], "daily_gift")      
    end  
    Broadcast.sendBroadcast(human, Lang.MOUSE, Lang.DAILY_GIFT_GET_OK)    
    RoleUIControl.sendLine1FnIcon(human)
end

function updateDaily(human)
    human.db.dailyGiftStatus = 0
    refreshThirdGrid(human)
end

function canShow(human)
    if human.db.dailyGiftStatus ~= 2 then
        return true
    end
end